const variables = this.getVariables();
const stream_url = `${window.location.origin}/streamUrl`;
const helper = new Helper(this);
const proxy = helper.getVariable('environmentType');
const videoPlatform = helper.getVariable('videoPlatform');
// 流媒体服务
const streamRequest = StreamServices.getInstance(proxy);
// 应急服务
const emergencyRequest = EmergencyServices.getInstance(proxy);

const _this = this;

console.log('页面初始化前: helper => ', helper)
// 公共请求方法
const baseRequest = function (url, body, method) {
    const controller = new AbortController();
    setTimeout(() => controller.abort(), 20000);
    const headers = { "Content-Type": "application/json" };
    const option = { method, headers, body: JSON.stringify(body), signal: controller.signal };
    return fetch(url, option).then(res => res.json());
}

// 监控视图数据处理
const handleMonitorData = async function () {
    const dataSource = [
        { id: "0", viewType: 0, viewName: "公有视图", monitorLevel: 'root' },
        { id: "1", viewType: 1, viewName: "私有视图", monitorLevel: 'root' }
    ];
    const res = await emergencyRequest.videoViewListByViewName(window._videoAccess.monitorSearch);
    const result = res.result || [];
    dataSource.forEach(item => {
        item.children = result.filter(i => i.viewType == item.viewType);
    });
    const monitor = _this.getApiWidgetByAliasName('monitor').widgetObj;
    monitor._option.dataSource = dataSource;
    monitor.render();
    console.log(dataSource, 'dataSource111')
    const monitorData = window._videoAccess.monitorSelect;
    console.log(monitorData, 'monitorData')
    if (monitorData?.id && monitorData?.operate !== 'delete') {
        const item = result.find(i => i.id === monitorData?.id);
        if (item) window._videoAccess.monitorSelect = item;
        const node = $(monitor.container).find(`#${window._videoAccess.monitorSelect?.id}`);
        node.addClass('tree_node_active');
    } else {
        window._videoAccess.monitorSelect = undefined;
    }
}

// 获取当前视频数据
const handleSullivanData = function () {
    const sullivan = helper.get('三维组件')?.widgetObj.sullivan;
    const cameraMap = sullivan.cameraMap || new Map();
    const grid = sullivan.grid || [3, 3];
    const videoViewDetails = [];
    cameraMap.forEach((item, index) => {
        const data = item.data || {};
        videoViewDetails.push({
            location: index,
            equipmentId: data?.equipmentCode,
            equipmentInfo: JSON.stringify(data),
        })
    })
    console.log(videoViewDetails, 'videoViewDetails')
    return { videoViewDetails, layout: JSON.stringify(grid) };
}

// 处理设备列表树数据
function handleRows(data, rows, id) {
    return data.map(item => {
        if (item.id === id) return { ...item, isFetch: true, children: rows };
        if (item.children && item.children.length) {
            return { ...item, children: handleRows(item.children, rows, id) }
        }
        return item;
    })
}

// 设置设备列表树数据
function renderTree(rows, id) {
    const areaTree = _this.getApiWidgetByAliasName('devices');
    const { dataSource } = areaTree.widgetObj._option
    const data = handleRows(dataSource, rows, id);
    console.log(data, rows, 'data')
    areaTree.widgetObj.setData([{ data }]);
    areaTree.widgetObj.render();
}

// 设备数据处理
function handleEquipmentData(data) {
    const { equipmentName, equipmentCode, equipmentId, equipmentConfig } = data || {};
    const gbVideoConfig = equipmentConfig?.gbVideoConfig || {};
    let channelId = gbVideoConfig?.videoChannelId;
    let deviceId = gbVideoConfig?.sipUser;
    let stream_path;
    if (channelId && deviceId) stream_path = `${deviceId}/${channelId}`;

    return {
        ...data,
        title: equipmentName,
        stream_path,
        channelId,
        deviceId,
        equipmentId: equipmentId || equipmentCode,
        url: `${stream_url}/api/v1/stream/rtc/play`,
    }
}

function handleFuseData(data) {
    return {
        ...data,
        title: data.fuseName,
        type: 'fuse',
        iconType: 'fuse',
        url: `${stream_url}/api/v1/stream/rtc/play`,
    }
}

// 区域数据处理
function handleAreaData(data, projectCode) {
    if (!data || !data.length) return [];
    return data.map(item => ({
        id: item.id,
        title: `${item.projectAreaName}(${item.equipmentCount})`,
        type: 'area',
        projectCode,
        children: [],
    }))
}

// 查询区域数据
const queryAreaData = async (id, projectCode) => {
    const url = `/${proxy}Basics/basics-main/system/equipmentObject/selectListByParentId`;
    // const loading = layer.load(0);
    // const res = await baseRequest(`${url}?equipmentTypeCode=camera&parentProjectAreaId=${id}&equipmentName=${_videoAccess.equipmentSearch}`);
    const res = await baseRequest(url, {
        projectCode,
        parentProjectAreaId: id,
        equipmentTypeCode: 'camera',
        equipmentName: _videoAccess.equipmentSearch,
    }, 'POST');
    // layer.close(loading);
    const areaRows = handleAreaData(res?.result?.areaList, projectCode);
    const equipmentRows = (res?.result?.equipmentList || []).map(item => handleEquipmentData(item));
    return { areaRows, equipmentRows };
}

// 查询区域数据 - 新版本接口
const queryQuotaByArea = async (id, projectCode) => {
    const url = `/${proxy}SummaryAssessmentSV/videoView/query/equipmentPointQuotaByProjectLocationArea`;
    // const loading = layer.load(0);
    // const res = await baseRequest(`${url}?equipmentTypeCode=camera&parentProjectAreaId=${id}&equipmentName=${_videoAccess.equipmentSearch}`);
    const res = await baseRequest(url, {
        projectCode,
        parentProjectAreaId: id,
        equipmentTypeCode: 'camera',
        equipmentName: _videoAccess.equipmentSearch,
    }, 'POST');
    // layer.close(loading);
    const { areaList = [], equipmentList = [], videoFuses = [] } = res?.result || {}
    const areaRows = handleAreaData(areaList, projectCode);
    const equipmentRows = (equipmentList).map(item => handleEquipmentData(item));
    const fusesRows = (videoFuses).map(item => handleFuseData(item));
    return { areaRows, equipmentRows, fusesRows };
}

// 查询融合视频数据
const queryFuseData = async (projectCode) => {
    const url = `/${proxy}SummaryAssessmentSV/videoFuse/query`;
    // const loading = layer.load(0);
    const res = await baseRequest(url, { projectCode, fuseName: _videoAccess.equipmentSearch }, 'POST');
    // layer.close(loading);
    return (res?.result || []).map(item => ({
        ...item,
        title: item.fuseName,
        type: 'fuse',
    }));
}

// 查询维修中设备
const queryMaintenanceData = async (projectCode) => {
    const name = _videoAccess.equipmentSearch;
    const url = `/${proxy}Basics/basics-main/system/equipmentObject/listRepairingEquipment`;
    // const loading = layer.load(0);
    console.log('查询维修中设备: => ', projectCode)
    const res = await baseRequest(`${url}?projectCode=${projectCode}&equipmentName=${name}&equipmentTypeCode=camera`);
    // layer.close(loading);
    return (res?.result?.rows || []).map(item => ({ ...handleEquipmentData(item), type: 'maintenance' }));
}


// 设备树数据处理
const handleEquipmentTreeData = async function () {
    const url = `/${proxy}SummaryAssessmentSV/videoView/query/equipmentPointQuotaStatus`;
    const body = {
        equipmentName: window._videoAccess.equipmentSearch,
        equipmentTypeCode: "camera"
    }
    // const loading = layer.load(0);
    const res = await baseRequest(url, body, 'POST');
    // layer.close(loading);
    const result = res?.result || [];
    const dataSource = result.map(item => {
        const fuseData = {
            title: `视频融合(${item.videoFuseCount})`,
            type: 'fuse-video',
            id: item.projectCode + '-fuse',
            projectCode: item.projectCode,
            children: [],
        };
        const maintenanceData = {
            title: `维修中(${item.maintenanceEquipmentPointQuotaInfo})`,
            type: 'maintenance-video',
            id: item.projectCode + '-maintenance',
            projectCode: item.projectCode,
            children: [],
        }
        const areaData = handleAreaData(item.areaResponseList, item.projectCode) || [];
        return {
            title: `${item.projectName}(${item.equipmentTotal})`,
            id: item.projectCode,
            isFetch: true,
            children: [fuseData, ...areaData, maintenanceData],
        };
    })
    console.log(dataSource, 'dataSource222')
    const devices = _this.getApiWidgetByAliasName('devices').widgetObj;
    devices.option_data = dataSource;
    devices.tree.expandSelected = new Set();
    devices.render();
}

// 查询海康视频流
async function getHikData(params) {
    const { expand, protocol = "hls,rtsp", streamType = 0, streamform, transmode = 0 } = params;
    let equipmentId = params.equipmentId || params.equipmentCode;
    let url = `/${proxy}IotDdevice/project-business-iot-service/hikvision/sec/video/equipmentId/preview/url/ext`;
    url = url.replace('equipmentId', equipmentId);
    const body = {
        cameraIndexCode: equipmentId,
        expand,
        protocol,
        streamType,
        streamform,
        transmode
    }
    const res = await baseRequest(url, body);
    return res?.result?.url ? JSON.parse(res.result.url) : false;
}


// 查询视频融合流地址
async function getFuse(data) {
    layer.msg('融合视频加载中');
    const fuseDetails = (data.videoFuseDetails || []).map(item => JSON.parse(item.equipmentInfo));
    return await getFuseByEquipmentInfo(fuseDetails, data);
}
// 查询视频融合流地址
async function getFuseByEquipmentInfo(fuseDetails, data = {}) {
    layer.msg('融合视频加载中');
    // const loading = layer.load(0);
    let body = {};
    if (videoPlatform === 'security') {
        const hikData = await Promise.all(fuseDetails.map(item => getHikData(item)));
        const urls = (hikData || []).map(item => item.urls.rtsp);
        body = { "urls": urls, stream_path: data?.id };
    } else {
        const stream_path = fuseDetails.map(item => item.stream_path);
        body = { "local_stream_paths": stream_path, stream_path: data?.id };
    }
    const res = await baseRequest(`${stream_url}/api/v1/stream/stitch`, body, 'POST');
    // layer.close(loading);
    if (res?.state) return { ...data, ...res.data };
    layer.msg(res?.desc || '视频融合失败');
    return false;
}

// 视频融合 - 新增
function insertVideoFuse ([one, ...other] = []) {
    const { projectAreaCode, projectAreaName, projectCode, projectName } = one;
    const videoFuseDetails = [one, ...other].map(item => ({
        equipmentInfo: JSON.stringify(item),
        equipmentId: item.equipmentCode,
    }));
    const options = {
        projectCode, projectName,
        projectAreaCode, projectAreaName,
        // fuseCode,
        fuseName: '视频拼接',
        videoFuseDetails,
    }
    return emergencyRequest.insertVideoFuse(options).then(() => {

    })
}

// 视频融合 - 修改
function updateVideoFuse (form, fuseDetails) {
    const videoFuseDetails = fuseDetails.map(item => ({
        equipmentInfo: JSON.stringify(item),
        equipmentId: item.equipmentCode,
    }));

    const options = {
        ...form,
        id, videoFuseDetails, projectCode, projectName, fuseName, fuseCode
    }
    return emergencyRequest.updateVideoFuse(options).then(() => {
        layer?.msg('更新成功！');
    })
}

// 视频融合 - 删除
function removeVideoFuse (id) {
    return emergencyRequest.removeVideoFuse(id).then(() => {
        layer?.msg('删除成功！');
    })
}

// 添加视频
async function addPlayer(data, index) {
    console.log(data, index, 'data, index')
    const widgets = helper.get('三维组件');
    const sullivan = widgets.widgetObj.sullivan;
    if (data.type === 'maintenance') {
        layer.msg('设备维修中');
        return;
    } else if (data.type === 'fuse') {
        const res = await getFuse(data);
        if (!res) return;
        sullivan.setPlayer({
            ...res,
            type: 'fuse',
            playerType: 'webrtc',
            equipmentName: data.fuseName,
            url: `${stream_url}/api/v1/stream/rtc/play`
        }, index);
    } else {
        if (!data.stream_path) {
            layer?.msg('未找到摄像头配置！');
            return;
        }
        sullivan.setPlayer({
            ...data,
            equipmentId: data.equipmentId || data.equipmentCode,
        }, index);
        widgets.widgetObj.addCameraContext(data.equipmentCode);
        return true;
    }
}

// 设置云台
function handlePtzCtrl(data) {
    const ptzCtrl = _this.getApiWidgetByAliasName('ptz-ctrl');
    const ptzBg = _this.getApiWidgetByAliasName('ptz-background');
    const [deviceId, channelId] = (data?.stream_path || '').split('/');
    if (deviceId && channelId) {
        ptzCtrl.showWidget()
        ptzBg.showWidget()
        ptzCtrl.widgetObj.setPtzController({
            id: deviceId,
            channel: channelId,
            equipmentId: data.deviceId,
        })
    }
}

// 查询预置位
async function queryPrests(id) {
    let res;
    // const loading = layer.load(0);
    if (videoPlatform === 'security') { // 安防平台
        const url = `/${proxy}IotDdevice/project-business-iot-service/hikvision/sec/${id}/preset/search`;
        res = await baseRequest(url, { cameraIndexCode: id }, 'POST');
    } else { // 流媒体
        const url = `/${proxy}IotDdevice/project-business-iot-service/hikvision/sdk/queryPresets`;
        res = await baseRequest(url, { equipmentId: id }, 'POST');
    }
    // layer.close(loading);
    if (!res || !res.result) layer?.msg('获取预置位失败！');
    return (res?.result || []).map(item => ({
        ...item,
        sourceName: item.name,
        name: item.presetNum + '-' + item.name,
        value: item.presetNum
    }))
}

// 查询轮询/巡航
async function queryCruises(id) {
    let res;
    // const loading = layer.load(0);
    if (videoPlatform === 'security') { // 安防平台
        const url = `/${proxy}IotDdevice/project-business-iot-service/hikvision/sec/${id}/cruiseRoute/search`;
        res = await baseRequest(url, { cameraIndexCode: id }, 'POST');
    } else { // 流媒体
        const url = `/${proxy}IotDdevice/project-business-iot-service/hikvision/sdk/queryCruises`;
        res = await baseRequest(url, { equipmentId: id }, 'POST');
    }
    // layer.close(loading);
    return (res?.result || []).map(item => ({
        ...item,
        name: item.cruiseRoute + '-巡航路径' + item.cruiseRoute,
        value: item.cruiseRoute
    }));
}

// 设置预置位信息
async function handlePresets(id) {
    const formObj = _this.getApiWidgetByAliasName('form_14').widgetObj;
    // const data = formObj.getFormValue('form_14');
    // console.log(data, ' data')
    // const equipmentCode = data?.equipmentCode || '';
    let list = [];
    if (id) list = await queryPrests(id);
    formObj._option.options = { list };
    _videoAccess.controlData = { ..._videoAccess.controlData, type: 'preset', presetList: list };
    // // _this.setVariables([{ name: 'device_list', value: list }]);
    formObj.render();
    formObj.setFormData('form_14', { id });

    const optsform = _this.getApiWidgetsByClassName('opts-form');
    optsform.forEach(v => v.showWidget());

    const ptzTabObj = _this.getApiWidgetByAliasName('ptz_tabs')?.widgetObj;
    ptzTabObj._option.defaultKey = 'preset';
    ptzTabObj.render();

    const formWatchOut = _this.getApiWidgetByAliasName('form_watch_out');
    formWatchOut.hideWidget();

    const $play = _this.getApiWidgetByAliasName('play');
    handleDisable($play.widgetObj.container, true);
    $play.widgetObj.container.setAttribute('title', '转到预置位');
    const $edit = _this.getApiWidgetByAliasName('edit');
    handleDisable($edit.widgetObj.container, true);
    $edit.widgetObj.container.setAttribute('title', '设置预置位');
    const $clear = _this.getApiWidgetByAliasName('clear');
    $clear.widgetObj.container.setAttribute('title', '清除预置位');
}

// 设置轮询/巡航信息
async function handleCruises(id) {
    const formObj = _this.getApiWidgetByAliasName('form_14').widgetObj;
    // const data = formObj.getFormValue('form_14');
    let list = [];
    if (id) list = await queryCruises(id);
    formObj._option.options = { list };
    _videoAccess.controlData = { ..._videoAccess.controlData, type: 'cruise', cruiseList: list };
    formObj.render();
    formObj.setFormData('form_14', { id });

    const optsform = _this.getApiWidgetsByClassName('opts-form');
    optsform.forEach(v => v.showWidget());

    const formWatchOut = _this.getApiWidgetByAliasName('form_watch_out');
    formWatchOut.hideWidget();

    const $play = _this.getApiWidgetByAliasName('play');
    handleDisable($play.widgetObj.container, true);
    $play.widgetObj.container.setAttribute('title', '开始轮巡');
    const $edit = _this.getApiWidgetByAliasName('edit');
    handleDisable($edit.widgetObj.container, true);
    $edit.widgetObj.container.setAttribute('title', '设置轮巡路径');
    const $clear = _this.getApiWidgetByAliasName('clear');
    $clear.widgetObj.container.setAttribute('title', '清除轮巡路径');
}

async function handleWatchOut(id) {
    const formWatchOut = _this.getApiWidgetByAliasName('form_watch_out');
    formWatchOut.widgetObj.resetForm('form_watch_out');
    formWatchOut.showWidget();

    const optsform = _this.getApiWidgetsByClassName('opts-form');
    optsform.forEach(v => v.hideWidget());

    const stop = _this.getApiWidgetByAliasName('stop');
    stop.hideWidget();

    let list = [];
    if (id) list = await queryPrests(id);
    const formObj = _this.getApiWidgetByAliasName('form_14').widgetObj;
    formObj._option.options = { list: list.slice(0, 32) };
    formObj.render();
    formObj.setFormData('form_14', { id });

    console.log(videoPlatform, 'videoPlatform')
    if (videoPlatform !== 'media') {
        layer?.msg('暂不支持守望!');
        return;
    }
    const url = `/${proxy}IotDdevice/project-business-iot-service/hikvision/sdk/getParkAction?equipmentId=${id}`;
    const res = await baseRequest(url);
    if (res.success) {
        const result = res.result || {};
        window._videoAccess.watchOut = { time: result?.parkTime, id: result.id };
    }
}

// 切换云台显隐
function togglePtzShow() {
    const ptzTitle = _this.getApiWidgetByAliasName('ptz_title').widgetObj;
    const ptzModals = _this.getApiWidgetsByClassName('ptz-modal');
    const optsf = _this.getApiWidgetsByClassName('opts-form');
    const change = _this.getApiWidgetByAliasName('change')?.widgetObj
    change._option.defaultKey = 'preset';
    change.render();

    const $form144 = _this.getApiWidgetByAliasName('form_144');
    if (_videoAccess.ptzShow) {
        $(ptzTitle.container).parent().css({ bottom: 255 });
        ptzModals.forEach(v => v.showWidget());
        optsf.forEach(v => v.showWidget());
        $form144.hideWidget();
    }
}


// 按钮禁用
function handleDisable(dom, flag) {
    if (flag) {
        $(dom).css({ filter: 'invert(40%)', cursor: 'not-allowed', 'pointer-events': 'none' });
    } else {
        $(dom).css({ filter: 'unset', cursor: 'pointer', 'pointer-events': 'auto' });
    }
}

// 视频调阅页面全局属性/方法
window._videoAccess = {
    proxy, // 请求前缀
    monitorSearch: '', // 视图搜索值
    monitorSelect: undefined, // 视图当前选中项
    equipmentSearch: '', // 设备搜索值
    watchOut: {}, // 守望信息
    baseRequest,
    handleMonitorData,
    handleSullivanData,
    handleEquipmentTreeData,
    handleAreaData,

    // 融合视频
    handleEquipmentData,
    getFuse,
    getFuseByEquipmentInfo,
    insertVideoFuse,
    updateVideoFuse,
    removeVideoFuse,

    addPlayer,
    queryAreaData,
    queryQuotaByArea,
    queryFuseData,
    queryMaintenanceData,

    controlData: {}, // 视频控制信息
    renderTree,
    handlePtzCtrl,
    handlePresets,
    handleCruises,
    handleWatchOut,

    ptzShow: false,
    togglePtzShow,
    handleDisable,
}